import sys
from faker import Faker
from openpyxl import Workbook
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QWidget, QPushButton, QLineEdit, QDialog,QVBoxLayout
from PyQt5.QtCore import Qt, QSize, QPropertyAnimation, QRect
import tkinter as tk
import threading  # 用于后台线程
import pytz
import pymysql
import configparser
import webbrowser
import datetime  # Import datetime module
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QLineEdit, QLabel
from PyQt5.QtCore import Qt,QUrl
from PyQt5.QtGui import QFont, QPalette, QCursor, QIcon, QColor,QDesktopServices
import pandas as pd
import openpyxl
import time
import zipfile
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pyperclip
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import random
import string
from openpyxl import Workbook, load_workbook
import shutil
from tkinter import messagebox
from tkinter import ttk
from ftplib import FTP
import os
import sys
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from datetime import datetime
import pyautogui
import pyperclip

# 查询逻辑

exprint =  "system/print.xlsx"
excetostar = "system/system.xlsx"

today = datetime.now().strftime("%m%d")  # MMDD 格式
file_path1 = f"{"DmitAI"}{today}-{+1}"


def print_mail(self):
    print("mail")
    print("Auto mail for")
    workbook = openpyxl.load_workbook(excetostar)
    sheet = workbook.active  # 使用第一个工作表
    a5prox = sheet['A5'].value
    a6prox = sheet['A6'].value
    a7prox = sheet['A7'].value
    filesname = sheet['I1'].value
    ipclinksp = sheet['B15'].value
    cheakips = sheet['B16'].value
    print(filesname)
    # Proxy information
    proxy = a5prox
    username = a6prox
    random_str = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(12))
    proxy_auth = f"{username}-{random_str}:{a7prox}"

    # Generate a random user-agent for Google Chrome (Desktop)
    # Generate a random user-agent for Google Chrome (Desktop)

    def generate_chrome_user_agent():
        platforms = [
            "Windows NT 10.0; Win64; x64",  # Windows 10

            "Macintosh; Intel Mac OS X 10_15_7",

        ]
        # Generate realistic Chrome version
        major_version = random.randint(90, 115)  # Common versions for Chrome
        build_version = random.randint(0, 5000)
        patch_version = random.randint(0, 150)
        chrome_version = f"Chrome/{major_version}.0.{build_version}.{patch_version}"

        safari_version = "Safari/537.36"
        platform = random.choice(platforms)

        return f"Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) {chrome_version} {safari_version}"

    # Generate a random user-agent for Microsoft Edge (Desktop)
    #def generate_edge_user_agent():
        #platforms = [
          #  "Windows NT 10.0; Win64; x64",  # Windows 10

           # "Macintosh; Apple Mac OS X 12_0_1"
      #  ]
        # Generate realistic Edge version
        #major_version = random.randint(90, 115)  # Common versions for Edge
        #build_version = random.randint(0, 5000)
        #patch_version = random.randint(0, 150)
        #edge_version = f"Edg/{major_version}.0.{build_version}.{patch_version}"

       # safari_version = "Safari/537.36"
        #platform = random.choice(platforms)

        #return f"Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) {edge_version} {safari_version}"

    # Configure Chrome options with proxy
    chrome_options = ChromeOptions()
    chrome_options.add_argument(f'--proxy-server=socks5://{proxy}')
    chrome_options.add_argument(f'user-agent={generate_chrome_user_agent()}')

    # Configure Edge options with proxy
    #edge_options = EdgeOptions()
    #edge_options.add_argument(f'--proxy-server=socks5://{proxy}')
    #edge_options.add_argument(f'user-agent={generate_edge_user_agent()}')

    # Set up proxy authentication
    manifest_json = """
                                            {
                                                "version": "1.0.0",
                                                "manifest_version": 3,
                                                "name": "Chrome Proxy",
                                                "permissions": [
                                                    "proxy",
                                                    "tabs",
                                                    "unlimitedStorage",
                                                    "storage",
                                                    "<all_urls>",
                                                    "webRequest",
                                                    "webRequestBlocking"
                                                ],
                                                "background": {
                                                    "scripts": ["background.js"]
                                                }
                                            }
                                            """

    background_js = f"""
                                            var config = {{
                                                    mode: "fixed_servers",
                                                    rules: {{
                                                      singleProxy: {{
                                                        scheme: "http",
                                                        host: "{proxy.split(':')[0]}",
                                                        port: parseInt({proxy.split(':')[1]})
                                                      }},
                                                      bypassList: ["localhost"]
                                                    }}
                                                  }};

                                            chrome.proxy.settings.set({{value: config, scope: "regular"}}, function() {{}});

                                            function callbackFn(details) {{
                                                return {{
                                                    authCredentials: {{
                                                        username: "{proxy_auth.split(':')[0]}",
                                                        password: "{proxy_auth.split(':')[1]}"
                                                    }}
                                                }};
                                            }}

                                            chrome.webRequest.onAuthRequired.addListener(
                                                callbackFn,
                                                {{urls: ["<all_urls>"]}},
                                                ['blocking']
                                            );
                                            """

    # Create the extension zip file for proxy authentication
    plugin_file = 'proxy_auth_plugin.zip'
    with zipfile.ZipFile(plugin_file, 'w') as zp:
        zp.writestr("manifest.json", manifest_json)
        zp.writestr("background.js", background_js)

    # Randomly choose between Chrome and Edge browser
    browser_choice = random.choice(["chrome"])
    driver = None

    # 创建一个Faker对象，设置为英国风格
    fake = Faker('en_GB')
    # 生成虚拟的英国人信息
    first_name = fake.first_name()  # 名字
    last_name = fake.last_name()  # 姓氏
    gender = fake.random_element(elements=('Male', 'Female'))  # 性别
    address = fake.address()  # 地址
    city = fake.city()
    county = fake.county()  # 郡（county）
    postcode = fake.postcode()  # 邮编

    # 确保生成有效的英国手机号码
    def generate_valid_uk_phone_number():
        while True:
            # 第二位随机选择 '3', '4', '5', '7', '9' 中的一个
            second_digit = random.choice(['3', '4', '5', '7', '9'])
            # 生成9个随机数字
            phone_number = f"07{second_digit}{''.join([str(random.randint(0, 9)) for _ in range(8)])}"

            # 检查号码是否有效（长度必须为11位，且以'07'开头）
            if len(phone_number) == 11 and phone_number.startswith('07'):
                return phone_number

    # 生成有效的手机号码
    phone_number = generate_valid_uk_phone_number()


    dob = fake.date_of_birth()  # 出生日期
    email = fake.email().split('@')[0]  # 去掉邮箱中@及其后面的内容
    username = first_name[0].lower() + last_name.lower()  # 根据名字和姓氏生成用户名
    password = fake.password()  # 随机生成密码

    security_answer = fake.word()  # 安全问题答案

    file_path = "excel/" + file_path1 + ".xlsx"
    # 创建工作簿和工作表
    wb = Workbook()
    ws = wb.active  # 获取默认工作表

    ws['A1'] = first_name
    ws['A2'] = last_name
    ws['A3'] = gender
    ws['A4'] = address
    ws['A5'] = city
    ws['A6'] = county
    ws['A7'] = postcode
    ws['A8'] = phone_number
    ws['A10'] = email
    ws['A11'] = "********************************"

    ws['A13'] = username
    ws['A14'] = password
    ws['A15'] = security_answer

    ws['A12'] = file_path

    wb.save(f"excel/{file_path1}.xlsx")



    try:
        if browser_choice == "chrome":
            # 启动 Google Chrome
            print("Launching Google Chrome")
            chrome_options = webdriver.ChromeOptions()  # 创建一个 ChromeOptions 对象
            chrome_options.add_extension(plugin_file)  # 添加插件
            chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])  # 禁用自动化标识

            # 启动 Chrome 浏览器
            # 启动 Chrome 浏览器
            driver = webdriver.Chrome(options=chrome_options)
            # 打开 https://signup.mail.com/
            driver.get('https://signup.mail.com/')

            driver.execute_script("window.open('https://www.scamalytics.com', '_blank');")  # 使用 JavaScript 打开新的标签页
            # 获取所有打开的标签页句柄
            windows = driver.window_handles

            # 切换到新打开的标签页（假设新标签页是最后一个打开的）
            driver.switch_to.window(windows[-1])

            # 现在在新标签页中，进行操作，比如获取页面的标题
            print(driver.title)  # 打印新标签页的标题
            while True:
                try:

                    ipclinkw = driver.find_element(By.XPATH, ipclinksp)
                    ipclinkw.click()
                    break

                except NoSuchElementException:
                    print(f"have no cell，keeping...")  # 输出未找到元素的提示
                    time.sleep(1)  # 等待1秒后继续查找
                    # 等待几秒钟查看效果
            time.sleep(2)

            # 获取 XPath 指定的元素
            try:
                xpath_element = driver.find_element(By.XPATH, cheakips)
                element_value = xpath_element.text  # 获取元素文本内容

                print(element_value)

                score = element_value.replace("Fraud Score: ", "")
                print(score)  # 输出：2
                score = int(score)

                if score >= 8:
                    print("exit")
                    driver.quit()  # 关闭浏览器
                else:
                    print("save")
                    workbook = load_workbook(file_path)
                    worksheet = workbook.active

                    # 在 A1 位置写入数据
                    worksheet['I1'] = score
                    workbook.save(file_path)
                    workbook.close()
            except Exception as e:
                print("Error:", e)
            print("ok")


            # 关闭当前标签页（新标签页）
            driver.close()

            # 切换回原始标签页（如果需要）
            driver.switch_to.window(windows[0])

            # 打印当前页面标题
            print(driver.title)
            workbook = openpyxl.load_workbook(file_path)
            sheet = workbook.active  # 使用第一个工作表
            firstips = sheet['A1'].value
            seconame = sheet['A2'].value
            genders = sheet['A3'].value
            addresss = sheet['A4'].value
            citys = sheet['A5'].value
            countys = sheet['A6'].value
            postcodes = sheet['A7'].value
            phone_numbers = sheet['A8'].value
            emails = sheet['A10'].value
            usernames = sheet['A13'].value
            passwords = sheet['A14'].value
            security_answers = sheet['A15'].value



            workbook.save(file_path)
            print("done for profile")

            print("start print")
            workbook = openpyxl.load_workbook(exprint)
            sheet = workbook.active  # 使用第一个工作表
            apiemail = sheet["B1"].value
            mangard = sheet["B2"].value
            grilgard = sheet["B3"].value
            firstpath = sheet["B4"].value
            lastpath = sheet["B5"].value
            unikingdon = sheet["B6"].value
            monthi = sheet["B7"].value
            daythi = sheet["B8"].value
            years = sheet["B9"].value
            paswd1 = sheet["B10"].value
            paswd2 = sheet["B11"].value
            gbnuber = sheet["B12"].value
            numberthis = sheet["B13"].value
            emailcopys = sheet["B14"].value
            accepttcb = sheet["B15"].value
            emailsitcb = sheet["B16"].value
            passwtcb = sheet["B17"].value
            clinktcb = sheet["B18"].value
            myprofiletcb = sheet["B19"].value
            usernmptcb = sheet["B20"].value
            tcnqustion = sheet["B21"].value
            tcbansouw = sheet["B22"].value
            tcbclinkfor = sheet["B23"].value
            tcbadname = sheet["B24"].value
            tcbadress = sheet["B25"].value
            tcbbirth = sheet["B26"].value
            firstadd = sheet["B27"].value
            lastadd = sheet["B28"].value
            locationtcb = sheet["B29"].value
            citystcb = sheet["B30"].value
            countytcb = sheet["B31"].value
            postcosetcb = sheet["B32"].value
            tcbdays = sheet["B33"].value
            tcbmothis = sheet["B34"].value
            tcbyesris = sheet["B35"].value
            tcbsecurity = sheet["B36"].value
            tcbsecuriclink = sheet["B37"].value

            workbook.save(exprint)

            while True:
                try:
                    # 查找指定的输入框
                    emalinput = driver.find_element(By.XPATH, apiemail)
                    emalinput.send_keys(emails)  # 输入文本

                    if genders == "Female":
                        print("gril")
                        driver.find_element(By.XPATH, grilgard).click()
                        time.sleep(0.3)
                    else:
                        print("boy")
                        driver.find_element(By.XPATH, mangard).click()
                        time.sleep(0.3)

                    firstname = driver.find_element(By.XPATH, firstpath)
                    firstname.send_keys(firstips)  # 输入文本
                    time.sleep(0.3)
                    lastname = driver.find_element(By.XPATH, lastpath)
                    lastname.send_keys(seconame)  # 输入文本
                    time.sleep(0.3)
                    kingkom = driver.find_element(By.XPATH, unikingdon)
                    kingkom.send_keys("United Kingdom")  # 输入文本
                    time.sleep(0.3)
                    month = random.randint(1, 12)
                    month = int(month)
                    day = random.randint(1, 28)
                    day = int(day)
                    year = random.randint(1983, 2004)
                    year = int(year)
                    monthos = driver.find_element(By.XPATH, monthi)
                    monthos.send_keys(month)  # 输入文本
                    time.sleep(0.3)
                    dayfull = driver.find_element(By.XPATH, daythi)
                    dayfull.send_keys(day)
                    time.sleep(0.3)
                    yearfull = driver.find_element(By.XPATH, years)
                    yearfull.send_keys(year)
                    time.sleep(0.3)
                    file_path = file_path
                    workbook = openpyxl.load_workbook(file_path)
                    sheet = workbook.active  # 使用第一个工作表

                    # 将 value 填入到 A8 单元格
                    sheet["A9"] = month
                    sheet["B9"] = day
                    sheet["C9"] = year

                    # 保存修改后的文件
                    print("It Already Put Both To Excel")

                    paswore1 = driver.find_element(By.XPATH, paswd1)
                    paswore1.send_keys(passwords)
                    time.sleep(0.3)
                    passwore2 = driver.find_element(By.XPATH, paswd2)
                    passwore2.send_keys(passwords)
                    time.sleep(0.3)
                    gbdim = driver.find_element(By.XPATH, gbnuber)
                    gbdim.send_keys("GB")
                    time.sleep(0.3)
                    newnumber = driver.find_element(By.XPATH, numberthis)
                    newnumber.send_keys(phone_numbers)
                    time.sleep(0.3)

                    workbook.save(file_path)

                    break
                except NoSuchElementException:
                    print(f"have no cell，keeping...")  # 输出未找到元素的提示
                    time.sleep(1)  # 等待1秒后继续查找

            time.sleep(1)
            ############################copyemail###################

            while True:
                try:

                    tcbdamews = driver.find_element(By.XPATH, emailcopys)
                    tcbdamews.click()
                    # 等待指定的元素变为可见（超时时间为 10 秒）
                    element = WebDriverWait(driver, 10).until(
                        EC.visibility_of_element_located((By.XPATH, emailcopys)))

                    workbook = openpyxl.load_workbook(file_path)
                    sheet = workbook.active  # 使用第一个工作表
                    # 获取目标元素的文本内容
                    emailouttx = element.text

                    # 打印获取的文本内容
                    print(emailouttx)

                    # 将获取的文本内容写入到 Excel 表格的 A9 单元格中
                    sheet["A10"] = emailouttx

                    # 暂停 0.2 秒
                    time.sleep(0.2)
                    workbook.save(file_path)
                    break

                except NoSuchElementException:
                    print(f"have no cell，keeping...")  # 输出未找到元素的提示
                    time.sleep(1)  # 等待1秒后继续查找
                    # 等待几秒钟查看效果
            time.sleep(2)
            input("Press Enter to close the browser...")  # Keeps the browser open until the user presses Enter
        
    except Exception as e:

        print(f"An error occurred: {e}")